﻿using System;
using Google.Protobuf.WellKnownTypes;
using SqlSugar;
using NetMicro.Core.ApiFunction;
using NetMicro.Core.Extensions;
using NetMicro.Core.Helper;


namespace NetMicro.Domains
{
    /// <summary>
    /// 实体基类
    /// </summary>
    /// <typeparam name="TKey"></typeparam>
    public class EntityBase<TKey> : Entity<TKey>
    {
        /// <summary>
        /// 创建人Id
        /// </summary>

        public string CreateId { get; set; } = "";

        /// <summary>
        /// 创建人
        /// </summary>

        public string CreateName { get; set; } = "";

        /// <summary>
        /// 创建时间
        /// </summary>

        public long CreateTime { get; set; }

        /// <summary>
        /// 更新人Id
        /// </summary>

        public string UpdateId { get; set; } = "";

        /// <summary>
        /// 更新人
        /// </summary>

        public string UpdateName { get; set; } = "";

        /// <summary>
        /// 更新时间
        /// </summary>

        public long UpdateTime { get; set; }

    }

    /// <summary>
    /// long主键
    /// </summary>
    public class EntityBase : EntityBase<long>
    {

        /// <summary>
        /// 初始化
        /// </summary>
        public override void Init()
        {
            IsDeleted = false;
            Id = SnowflakeHelper.GetId();
            long data = TimeSpan.Zero.GetTimestampMilliseconds();
            CreateTime = data;
            CreateId = ApiContext.IsAdminApi ? ApiContext.AdminContext.AccountId ?? "" : ApiContext.WebContext.UserId ?? "";
            CreateName = ApiContext.IsAdminApi ? ApiContext.AdminContext.UserName ?? "" : "";
            UpdateTime = data;
            Version = 1;
        }
        /// <summary>
        /// 修改初始化
        /// </summary>
        /// <param name="entityBase"></param>
        public override void UpdateInit<EntityBase>(EntityBase entityBase)
        {
            IsDeleted = false;
            Version = entityBase.Version++;
            long data = TimeSpan.Zero.GetTimestampMilliseconds();
            UpdateTime = data;
            UpdateId = ApiContext.IsAdminApi ? ApiContext.AdminContext.AccountId ?? "" : ApiContext.WebContext.UserId ?? "";
            UpdateName = ApiContext.IsAdminApi ? ApiContext.AdminContext.UserName ?? "" : "";
        }

        /// <summary>
        /// 假删除初始化
        /// </summary>
        /// <param name="entityBase"></param>
        public override void SoftDeleteInit<EntityBase>(EntityBase entityBase)
        {
            IsDeleted = true;
            Version = entityBase.Version++;
            long data = TimeSpan.Zero.GetTimestampMilliseconds();
            UpdateTime = data;
            UpdateId = ApiContext.IsAdminApi ? ApiContext.AdminContext.AccountId ?? "" : ApiContext.WebContext.UserId ?? "";
            UpdateName = ApiContext.IsAdminApi ? ApiContext.AdminContext.UserName ?? "" : "";
        }


    }
}
